<?php
/**
 * SmsService.php
 * 文件描述
 * Created on 2020/9/4 10:42
 * Created by 刘小龙 595929049@qq.com
 */

namespace app\xiangji\services;
use app\common\models\UserPair;
use app\common\models\UserSignsRecord;
use app\common\services\SmsService as CommonSmsService;
use app\common\models\UserActivity;
use app\common\models\UserLoveWalletLog;
use app\common\models\UserloveWallet;
use app\common\facades\auth\Auth;

class ActivityService
{
    //1314活动的专属服务
    private $smsService;
    /**
     * 签到返红
     */
    const SIGN_RETURN_MONEY = "签到返红";

    public function __construct(CommonSmsService $smsService)
    {
        $this->smsService = $smsService;
    }

    /**
     * 每日获得的随机钱包0.1~1元 转化为分
     * @return float|int
     */
    public static function randWallet(){
        return rand(1,10)*10;
    }

    /**
     * 返回1314应得的金额
     * @return float|int
     */
    public static function foreverWallet(){
        return 1314 * 100;
    }

    /**
     *
     */
    public function loveWallet(){
        $user = Auth::guard('api')->user();
        $pairinfo = $this->pairInfo();
        return (new UserLoveWallet())->where(['is_available'=>1,'id'=>$pairinfo['id']])->find();
    }

    /**
     * 返回情侣的信息
     * @param $userid
     * @return bool|mixed
     */

    public function pairInfo(){
        $user = Auth::guard('api')->user();
        if($user->gender == 1){
            $where['male_id'] = $user->id;
        }elseif($user->gender == 0){
            $where['female_id'] = $user->id;
        }else{
            return  false;
        }
        $where['is_available'] = 1;
        return (new UserPair())->where($where)->find();
    }

    /**
     * 返回该对情侣的今天签到记录,没有则创建
     * @param $pairid
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    public function todaySign($pairid){
        $pairsign  = (new UserSignsRecord())->where(['is_available'=>1,'pair_id'=>$pairid,'sign_date'=>date('Y-m-d',time())])->find();
        if($pairsign){
            return  $pairsign;
        }else{
            $datainsert = [
                'pair_id'   =>  $pairid,
                'sign_date'=>date('Y-m-d',time()),
                'create_time'=>time(),
                'male_status'=>0,
                'female_status'=>0,
                'update_time'=>0,
                'delete_time'=>0,
                'is_wallet'=>0,
                'is_available'=>1
            ];
            $re = (new UserSignsRecord())->insertGetId($datainsert);
            $datainsert['id'] = $re;
            return  $re ? $datainsert : false;
        }
    }

    /**
     * 情侣签到
     * @param $useid
     */
    public function activitySign(){
        $pairData = $this->pairInfo();//获取该对情侣的数据
        if(!$pairData) return false;
        $user = Auth::guard('api')->user();
        $saveData = [];
        if($pairData['id']){
            $todaySign = $this->todaySign($pairData['id']);//今天的签到记录
            if($todaySign){
                if($todaySign['male_status'] == 1 && $todaySign['female_status'] == 1){
                    return false;
                }
                if($user->gender == 1 && $todaySign['male_status'] == 0){//当事人是男且男方未签到
                    $saveData['male_status'] = 1;
                    $saveData['update_time'] = time();
                    if($todaySign['female_status'] == 1){//如果女方已经签到，男方此次签到则两人都签到成功，则返红
                        if($todaySign['is_wallet'] == 0){//如果未领当天红包
                            $saveData['is_wallet'] = 1;//更改红包已领状态
                            Db::startTrans();
                            try {
                                $this->addLoveWallet($pairData['id'],self::foreverWallet(),self::SIGN_RETURN_MONEY);//将钱划入恋爱钱包
                                (new UserSignsRecord())->where(['id'=>$todaySign['id']])->save($saveData);//更改签到和红包已领状态
                            }catch (\Exception $e) {
                                // 回滚事务
                                Db::rollback();
                            }
                        }else{//红包已领则只改状态
                            (new UserSignsRecord())->where(['id'=>$todaySign['id']])->save($saveData);
                        }
                    }else{//女方未签到则只更新数据库
                        (new UserSignsRecord())->where(['id'=>$todaySign['id']])->save($saveData);
                    }
                }
                if($user->gender == 0 && $todaySign['female_status'] == 0){//当事人为女，且女方未签到
                    $saveData['female_status'] = 1;
                    $saveData['update_time'] = time();
                    if($todaySign['male_status'] == 1){//如果男方已经签到，女方此次签到则两人都签到成功，则返红
                        if($todaySign['is_wallet'] == 0){//如果未领当天红包
                            $saveData['is_wallet'] = 1;//更改红包已领状态
                            Db::startTrans();
                            try {
                                $this->addLoveWallet($pairData['id'],self::foreverWallet(),self::SIGN_RETURN_MONEY);//将钱划入恋爱钱包
                                (new UserSignsRecord())->where(['id'=>$todaySign['id']])->save($saveData);//更改签到和红包已领状态
                            }catch (\Exception $e) {
                                // 回滚事务
                                Db::rollback();
                            }
                        }else{//红包已领则只改状态
                            (new UserSignsRecord())->where(['id'=>$todaySign['id']])->save($saveData);
                        }
                    }else{//男方未签到则只更新数据库
                        (new UserSignsRecord())->where(['id'=>$todaySign['id']])->save($saveData);
                    }
                }
            }else{
                return  false;
            }
        }
    }

    /**
     * 判断该情侣对是否有资格进行1314活动
     * @param $pair_id 情侣对的id
     * @return bool
     */

    public function authActivity($pair_id){
        $UserActivity = new UserActivity();
        $end_time = $UserActivity->where([
            'is_available'  => 1,
            'pair_id'       =>$pair_id
        ])->value("end_time");
        if(!$end_time || $end_time < time()) return false;
        return true;
    }
    /**
     * 钱包加钱
     * @param $pair_id
     * @param $addmoney
     * @param string $sence
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    public function addLoveWallet($pair_id,$addmoney,$sence = "获得红包"){
        $LoveWallet = new UserLoveWallet();
        $now  = $LoveWallet->where(['pair_id' => $pair_id,'is_available' => 1])->find();
        if(!$now) return false;
        Db::startTrans();
        try {
            //恋爱钱包加钱
            $LoveWallet->where([
                'id'  =>   $now['id']
            ])->save([
                'balance'=> $now['balance'] + $addmoney,
                'income' =>$now['income'] + $addmoney,
                'update_time'=>time()
            ]);
            $this->addLoveWalletLog($now['id'],$addmoney,self::SENCE.$addmoney,$now['balance'],$now['balance'] + $addmoney);//添加日志
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }

    }

    /**
     * 添加恋爱钱包日志
     * @param $love_wallet_id 恋爱钱包id
     * @param $changes
     * @param $scene
     * @param $amount_before
     * @param $amount_after
     * @return UserLoveWalletLog|\think\Model
     */

    public function addLoveWalletLog($love_wallet_id,$changes,$scene,$amount_before,$amount_after){
        $UserLoveWalletLog = new UserLoveWalletLog();
        return $UserLoveWalletLog::create([
            'love_wallet_id'    =>  $love_wallet_id,
            'changes'           =>  $changes,
            'scene'             =>  $scene,
            'amount_before'     =>  $amount_before,
            'amount_after'      =>  $amount_after,
            'create_time'       =>  time()
        ]);
    }
}
